package com.easy.service.impl;

import com.easy.bean.Review;
import com.easy.mapper.ReviewDao;
import com.easy.service.ReviewService;
import com.easy.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class ReviewServiceImpl implements ReviewService {

    private static final String CACHE_NAME = "review";

    @Autowired
    ReviewDao reviewDao;

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'review:' + #p0.id", condition = "#result != null")
    public Review add(Review review) {
        // 新增数据
        reviewDao.add(review);
        // 通过主键查询数据库的数据
        Review result = reviewDao.one(review.getId());
        return result;
    }

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'review:id:' + #p0")
    public int del(Integer id) {
        return reviewDao.del(id);
    }

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'review:' + #p0.id", condition = "#p0 != null and #p0.id != null")
    public Review edit(Review review) {
        reviewDao.edit(review);
        Review result = reviewDao.one(review.getId());
        return result;
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'review:list:' + T(java.util.Objects).hash(#p0)", unless = "#result == null or #result.isEmpty()")
    public List<Review> all(Review review) {
        return reviewDao.all(review);
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'review:id:' + #p0", unless = "#result == null")
    public Review one(Integer id) {
        return reviewDao.one(id);
    }

    @Override
    public void page(Page page, Review review) {
        int count = reviewDao.pageCount(review);
        Object data = reviewDao.page(page, review);
        page.setCount(count);
        page.setData(data);
    }

    @Override
    public void pageWithDetails(Page page, Review review) {
        int count = reviewDao.pageCountWithDetails(review);
        Object data = reviewDao.pageWithDetails(page, review);
        page.setCount(count);
        page.setData(data);
    }

}
